package com.heima.media.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import com.heima.common.dto.ResponseResult;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmSensitive;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsService;
import com.heima.media.service.IWmSensitiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private IAuditService auditService;
    @Autowired
    private IWmNewsService newsService;
    @Autowired
    private IWmSensitiveService sensitiveService;

    /**
     * 测试自动审核接口
     * @param id
     * @return
     */
    @GetMapping("/audit/{id}")
    public ResponseResult audit(@PathVariable("id") Integer id) {

        WmNews wmNews = newsService.getById(id);
        // 传入文章对象
        auditService.audit(wmNews);
        return ResponseResult.okResult();
    }


    /**
     * 敏感词导入
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/read")
    @ResponseBody
    public String read(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), WmSensitive.class, new ReadListener<WmSensitive>() {

            @Override
            public void invoke(WmSensitive data, AnalysisContext context) {
                // 读取每一行数据触发
                System.out.println(data);
                // todo 更新到数据库,判断当前敏感词是否已经存在,不存在新增
                //查询数据库中所有的敏感词
                //添加是否相同的标记
                boolean isEqual = false;
                List<WmSensitive> list = sensitiveService.list();
                if (list != null) {
                    for (WmSensitive wmSensitive : list) {
                        if (wmSensitive.getSensitives().equals(data.getSensitives())) {
                            isEqual = true;
                            break;
                        }
                    }
                }
                if (isEqual == false) {
                    //敏感词不存在，封装敏感词对象插入数据库
                    WmSensitive wmSensitive = new WmSensitive();
                    wmSensitive.setSensitives(data.getSensitives());
                    wmSensitive.setCreatedTime(new Date());
                    sensitiveService.save(wmSensitive);
                }

            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                // 全部读取完成触发
                System.out.println("全部处理完成");

            }
        }).sheet().doRead();

        return "success";
    }


    /**
     * 文件下载并且失败的时候返回json（默认失败了会返回一个有部分数据的Excel）
     *
     * @since 2.1.1
     */
    @GetMapping("/downloadFailedUsingJson")
    public void downloadFailedUsingJson(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("敏感词导出测试", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), WmSensitive.class).autoCloseStream(Boolean.FALSE).sheet("模板")
                    .doWrite(data());
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    private List<WmSensitive> data() {

        return sensitiveService.list();

    }

}
